using System;
using System.Windows.Forms;
using System.Collections;
namespace Utilities
{
	// An instance of the SortWrapper class is created for
	// each item and added to the ArrayList for sorting.
	public class SortWrapper
	{
		internal ListViewItem sortItem;
		internal int sortColumn;

		// A SortWrapper requires the item and the index of the clicked column.
		public SortWrapper (ListViewItem Item, int iColumn)
		{
			sortItem = Item;
			sortColumn = iColumn;
		}

		// Text property for getting the text of an item.
		public string Text
		{
			get
			{
				return sortItem.SubItems[sortColumn].Text;
			}
		}

		// Implementation of the IComparer
		// interface for sorting ArrayList items.
		public class SortComparer : IComparer
		{
			bool ascending;
            private bool numeric;

            public bool Numeric
            {
                get { return numeric; }
                set { numeric = value; }
            }
			// Constructor requires the sort order;
			// true if ascending, otherwise descending.
			public SortComparer(bool asc,bool number)
			{
				this.ascending = asc;
                Numeric = number;
			}

			// Implemnentation of the IComparer:Compare
			// method for comparing two objects.
			public int Compare(object x, object y)
			{
                SortWrapper listX = (SortWrapper)x;
                SortWrapper listY = (SortWrapper)y;

                if (Numeric)
                {
                    decimal listXVal, listYVal;
                    try
                    {
                        listXVal = Decimal.Parse(listX.sortItem.SubItems[listX.sortColumn].Text);
                        listYVal = Decimal.Parse(listY.sortItem.SubItems[listY.sortColumn].Text);
                    }
                    catch
                    {
                        string listXText = listX.sortItem.SubItems[listX.sortColumn].Text;
                        string listYText = listY.sortItem.SubItems[listY.sortColumn].Text;
                        return String.Compare(listXText, listYText) * (this.ascending ? 1 : -1);
                    }
                    return Decimal.Compare(listXVal, listYVal) * (this.ascending ? 1 : -1);
                }
                else
                {
                    string listXText = listX.sortItem.SubItems[listX.sortColumn].Text;
                    string listYText = listY.sortItem.SubItems[listY.sortColumn].Text;
                    return String.Compare(listXText, listYText) * (this.ascending ? 1 : -1);
                }
			}
		}
	}
}